package clue

import (
	"encoding/json"
	"git.mycaigou.com/gfyx/common/authorize"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/service/base/user/user_service"
	report2 "git.mycaigou.com/gfyx/micro-gfyx-mp-api/service/clue/report"
	"strconv"
	"strings"

	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/http_server/controller"
	reportDto "git.mycaigou.com/gfyx/micro-gfyx-mp-api/http_server/dto/report"
	"git.mycaigou.com/gfyx/micro-gfyx-mp-api/infrastructure/common/errcode"
	microGfyxUserService "git.mycaigou.com/gfyx/micro-gfyx-mp-api/proto/micro_gfyx_user_service_proto/micro-gfyx-user-service"
	"git.myscrm.cn/golang/stark/v4"
	"github.com/gin-gonic/gin"
)

type ReportController struct {
	controller.BaseController
	reportService report2.ReportServiceIface
	userService   user_service.UserSerivceIface
}

// NewReportController 构造函数
func NewReportController(reportService report2.ReportServiceIface,
	userService user_service.UserSerivceIface) *ReportController {
	return &ReportController{reportService: reportService, userService: userService}
}

// RegisterRouter
// 注册路由
func (c *ReportController) RegisterRouter(g *gin.RouterGroup) {
	// 模板相关
	g.GET("/get-form-template", c.GetFormTemplateConfig)
	g.GET("/get-form-data-rule", c.GetFormDataRule)
	g.GET("/get-user-list", c.GetReportUser)
	// 生成分享链接
	g.POST("/generate-url", c.GenerateUrl)

	// 领取分享链接
	g.POST("/receive-url", c.ReceiveUrl)

	// 未付费，报备列表
	g.GET("/report-list", c.ReportList)

	// 报备列表
	g.POST("/report-info", c.ReportInfo)

	// 报备提交
	g.POST("/report-save", c.Save)

	// 报备列表-联系人
	g.GET("/search-contacts", c.SearchContacts)

	// 负责人
	g.GET("/get-team-leader", c.GetTeamLeader)

	// 报备列表-填充表单
	g.GET("/fill-report-form", c.FillReportForm)

	g.POST("/report-follow-save", c.SaveFollowRecord)
	g.GET("/report-follow-list", c.GetFollowRecordList)

	// 获取报备详情
	g.GET("/detail", c.GetReport)

	// 已付费用户，我的报备列表接口
	g.GET("/get-my-list", c.GetMyList)
	// 已付费用户，区域报备、全国报备列表接口
	g.GET("/get-region-list", c.GetRegionList)

	// 获取报备、线索统计
	g.GET("/report-stat", c.GetReportStat)

}

//
//func (c *ReportController) SetTenantCodeWithReportUrl(ctx *gin.Context) {
//	tenantCode := authorize.GetTenantCode(ctx)
//	if tenantCode == "" {
//		urlUid := ctx.Request.Header.Get("url_uid")
//		_ = c.reportService.SetTenantCodeWithReportUrl(ctx, urlUid)
//	}
//}

// GetFormTemplateConfig 获取模板配置
func (c *ReportController) GetFormTemplateConfig(ctx *gin.Context) {
	//c.SetTenantCodeWithReportUrl(ctx)
	templateId := ctx.Request.Header.Get("template_id")
	//配置化模板暂未实现
	templateId = ""

	data, err := c.reportService.GetFormTemplateConfig(ctx, templateId)
	if err != nil {
		stark.Logger.Errorf(ctx, "获取模板配置接口出错", err.Error())
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	if data == nil {
		var emptyData []string
		c.Success(ctx, emptyData)
		return
	}

	c.Success(ctx, data)
	return
}

// GetFormDataRule
// @Summary 获取数据校验规则
// @ID get-form-data-rule
// @Param key query string false "规则key,多个key以半角逗号分割，如果为空，则返回全部key"
// @Success 200 {object} Data
func (c *ReportController) GetFormDataRule(ctx *gin.Context) {
	//c.SetTenantCodeWithReportUrl(ctx)
	data, err := c.reportService.GetFormDataRule(ctx, "")
	if err != nil {
		stark.Logger.Errorf(ctx, "获取数据校验规则接口出错", err.Error())
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	if data == nil {
		var emptyData []string
		c.Success(ctx, emptyData)
		return
	}

	c.Success(ctx, data)
	return
}

func (c *ReportController) GetReportUser(ctx *gin.Context) {
	result, err := c.reportService.GetReportUserList(ctx)
	if err != nil {
		stark.Logger.Errorf(ctx, "获取用户信息列表错误，错误信息：%v", err)
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	c.Success(ctx, result["list"])
}

func (c *ReportController) GenerateUrl(ctx *gin.Context) {
	globalUserId := authorize.GetGlobalUserId(ctx)
	if globalUserId == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "用户编号为空")
		return
	}

	var params = make(map[string]interface{})
	err := json.NewDecoder(ctx.Request.Body).Decode(&params)

	if err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "无法解析传入的参数")
		return
	}

	rs := &report2.ReportShare{
		TenantCode:         authorize.GetTenantCode(ctx),
		SharerUserId:       globalUserId,
		SharerUserTenantId: authorize.GetTenantUserId(ctx),
		SharerUserName:     authorize.GetUserName(ctx),
		SharerUserCode:     authorize.GetUserCode(ctx),
		SharerUserMobile:   authorize.GetMobilePhone(ctx),
	}

	if val, ok := params["clue_source"]; ok {
		rs.ClueSource = val.(string)
	} else {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "没有传clue_source")
		return
	}

	if val, ok := params["clue_source_id"]; ok {
		rs.ClueSourceId = val.(string)
	} else {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "没有传clue_source_id")
		return
	}

	// 加载数据
	request := &reportDto.FillReportFormRequest{}
	request.ClueSource = rs.ClueSource
	request.ClueSourceId = rs.ClueSourceId
	reportForm, err := c.reportService.FillReportForm(ctx, request)

	if err != nil {
		stark.Logger.Errorf(ctx, "GenerateUrl-error: %+v, clue_source_id: %s", err.Error(), request.ClueSourceId)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	rs.ClueSourceTitle = reportForm["report_source_title"].(string)
	if reportForm["project_title"] == "" {
		rs.CityCode = reportForm["company_city_code"].(string)
		rs.ProvinceCode = reportForm["company_province_code"].(string)
	} else {
		rs.CityCode = reportForm["project_city_code"].(string)
		rs.ProvinceCode = reportForm["project_province_code"].(string)
	}
	rs.CompanyName = reportForm["company_name"].(string)

	// 生成链接
	code, err := c.reportService.GenerateUrl(ctx, rs)
	if err != nil {
		stark.Logger.Errorf(ctx, "GenerateUrl-error: %+v, userid: %s", err.Error(), globalUserId)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	c.Success(ctx, code)
}

func (c *ReportController) ReceiveUrl(ctx *gin.Context) {
	globalUserId := authorize.GetGlobalUserId(ctx)
	if globalUserId == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "用户编号为空")
		return
	}

	request := &reportDto.ReceiveUrlRequestDto{}
	if err := ctx.ShouldBind(request); err != nil {
		stark.Logger.Errorf(ctx, "错误code:", errcode.COMMON_PARAMS_ERROR, ",错误msg:,", err)
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "参数异常")
		return
	}

	isSuccess, err := c.reportService.ReceiveUrl(ctx, globalUserId, request.Code)
	if err != nil {
		stark.Logger.Errorf(ctx, "ReceiveUrl-error: %+v, userid: %s", err.Error(), globalUserId)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	c.Success(ctx, isSuccess)
}

func (c *ReportController) ReportList(ctx *gin.Context) {
	globalUserId := authorize.GetGlobalUserId(ctx)
	if globalUserId == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "用户编号为空")
		return
	}

	request := &reportDto.ReportFromSharingListRequestDto{}
	if err := ctx.ShouldBind(request); err != nil {
		stark.Logger.Errorf(ctx, "ReportList 参数错误:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "参数异常")
		return
	}

	request.RecipientUid = globalUserId
	total, list, err := c.reportService.ReportList(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "ReportList-error: %+v, userid: %s", err.Error(), globalUserId)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	c.Success(ctx, map[string]interface{}{"total": total, "list": list})
}

func (c *ReportController) ReportInfo(ctx *gin.Context) {

	request := &reportDto.ReportInfoRequestDto{}
	if err := ctx.ShouldBind(request); err != nil {
		stark.Logger.Errorf(ctx, "ReportInfo 参数错误:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "参数异常")
		return
	}

	reportInfo, err := c.reportService.ReportInfo(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "ReportInfo-error: %+v, request: %+v", err.Error(), request)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	c.Success(ctx, reportInfo)
}

func (c *ReportController) SearchContacts(ctx *gin.Context) {

	request := &reportDto.ReportOptionRequest{}
	request.OrganizingCode = ctx.Query("organizing_code")
	request.ClueSource = ctx.Query("clue_source")
	request.ClueSourceId = ctx.Query("clue_source_id")
	request.Keyword = ctx.Query("keyword")
	page, err := strconv.Atoi(ctx.Query("page"))
	if err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "没有传递page")
		return
	}
	request.Page = int32(page)
	pageSize, err := strconv.Atoi(ctx.Query("page_size"))
	if err != nil {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "没有传递page_size")
		return
	}
	request.PageSize = int32(pageSize)

	contracts, err := c.reportService.SearchContacts(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "SearchContacts-error: %s, request: %+v", err.Error(), request)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	// 避免空指针错误
	if contracts == nil {
		c.Success(ctx, map[string]interface{}{"totalNum": 0, "pageSize": pageSize, "pageNum": page, "rows": []interface{}{}})
	}

	c.Success(ctx, contracts.Data)
}

// GetTeamLeader @Summary 获取报备负责人团队
func (c *ReportController) GetTeamLeader(ctx *gin.Context) {
	// 如果是未付费用户
	//c.SetTenantCodeWithReportUrl(ctx)
	reportId := ctx.Query("report_id")
	if reportId == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "report_id不能为空")
		return
	}

	result, err := c.reportService.GetTeamLeader(ctx, reportId)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetTeamLeader 获取报备负责团队reportId:%s，错误信息：%v", reportId, err)
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}
	c.Success(ctx, result)
}

func (c *ReportController) FillReportForm(ctx *gin.Context) {
	globalUserId := authorize.GetGlobalUserId(ctx)
	if globalUserId == "" {
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "用户编号为空")
		return
	}

	request := &reportDto.FillReportFormRequest{}
	request.ClueSource = ctx.Query("clue_source")
	request.ClueSourceId = ctx.Query("clue_source_id")

	reportForm, err := c.reportService.FillReportForm(ctx, request)
	if err != nil {
		stark.Logger.Errorf(ctx, "FillReportForm-error: %s,globalUserId: %s, request: %+v", err.Error(), globalUserId, request)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	loginInfo, err := c.userService.GetUserInfoByGlobalUserId(ctx, globalUserId)
	if err != nil {
		stark.Logger.Errorf(ctx, "FillReportForm-GetUserInfoByGlobalUserId-error: %s,globalUserId: %s, request: %+v", err.Error(), globalUserId, request)
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	// 增加空指针检查
	if loginInfo != nil && loginInfo.UserInfo != nil {
		reportForm["submitter"] = loginInfo.UserInfo.UserName
		reportForm["submitter_tel"] = loginInfo.UserInfo.Mobile

		if len(loginInfo.TenantList) > 0 {
			reportForm["submitter_company"] = loginInfo.TenantList[0].TenantName
		}
	}

	c.Success(ctx, reportForm)
}

func (c *ReportController) SaveFollowRecord(ctx *gin.Context) {
	// 如果是未付费用户
	//c.SetTenantCodeWithReportUrl(ctx)

	req := reportDto.SaveFollowRecordRequest{}
	if err := ctx.ShouldBind(&req); err != nil {
		stark.Logger.Errorf(ctx, "SaveFollowRecord 参数错误:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_ERROR, "参数不合法")
		return
	}

	urlUid := ctx.Request.Header.Get("url_uid")
	existUrlUid := len(urlUid) > 0
	if existUrlUid {
		dto := &reportDto.ReportInfoRequestDto{
			Code: urlUid,
		}
		ri, err := c.reportService.ReportInfo(ctx, dto)
		if err != nil {
			stark.Logger.Errorf(ctx, "url_uid获取信息失败，err:%v", err)
			c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
			return
		}
		// 模拟租户用户，notice：只篡改了用户名，后续使用该接口时请注意
		ctx.Set(authorize.TENANT_USER_NAME, ri.SubmitterName)
	} else {
		dto := &reportDto.ReportInfoRequestDto{
			ReportId: req.ReportId,
		}
		ri, err := c.reportService.ReportInfo(ctx, dto)
		if err != nil {
			stark.Logger.Errorf(ctx, "url_uid获取信息失败，err:%v", err)
			c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
			return
		}
		urlUid = ri.Uid
		existUrlUid = len(urlUid) > 0
	}

	if err := c.reportService.SaveFollowRecord(ctx, &req); err != nil {
		stark.Logger.Errorf(ctx, "SaveFollowRecord request:%+v, err:%s", req, err.Error())
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}

	if existUrlUid && (req.FollowStatus == 1 || req.FollowStatus == 2 || req.FollowStatus == 3) {
		globalUserId := authorize.GetGlobalUserId(ctx)
		updateData := &microGfyxUserService.ReportFromSharing{
			ReportStatusCode: req.FollowStatus,
		}
		if req.FollowStatus == 2 {
			updateData.ReportStatus = "已签约"
		} else if req.FollowStatus == 3 {
			updateData.ReportStatus = "未签约"
		} else if req.FollowStatus == 1 {
			updateData.ReportStatus = "跟进中"
		}

		_, err := c.reportService.UpdateReportShare(ctx, globalUserId, urlUid, updateData)
		if err != nil {
			stark.Logger.Errorf(ctx, "SaveFollowRecord-UpdateReportShare request:%+v, globalUserId:%s, urlUid:%s, updateData:%+v, err:%s",
				req, globalUserId, urlUid, updateData, err.Error())
			c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
			return
		}
	}
	c.Success(ctx, map[string]interface{}{})
}

func (c *ReportController) GetFollowRecordList(ctx *gin.Context) {
	// 如果是未付费用户
	//c.SetTenantCodeWithReportUrl(ctx)

	reportId := ctx.Query("report_id")
	page := ctx.DefaultQuery("page", "1")
	pageSize := ctx.DefaultQuery("page_size", "10")

	p, _ := strconv.Atoi(page)
	ps, _ := strconv.Atoi(pageSize)
	list, total, err := c.reportService.GetFollowRecordList(ctx, reportId, int32(p), int32(ps))
	if err != nil {
		stark.Logger.Errorf(ctx, "GetFollowRecordList reportId:%s, page:%d,pageSize:%d, err:%s", reportId, p, ps, err.Error())
		c.Fail(ctx, errcode.COMMON_DATA_NOT_EXIST, err.Error())
		return
	}
	data := map[string]interface{}{
		"total": total,
		"list":  list,
	}
	c.Success(ctx, data)
}

func (c *ReportController) Save(ctx *gin.Context) {
	// 提前知道是否是付费用户
	tenantUserUid := authorize.GetTenantUserId(ctx)
	// 如果是未付费用户
	//c.SetTenantCodeWithReportUrl(ctx)

	var requestDto reportDto.SaveRequest
	err := ctx.ShouldBind(&requestDto)
	if err != nil {
		stark.Logger.Infof(ctx, "Save 参数错误 err:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "参数错误")
		return
	}

	urlUid := ctx.Request.Header.Get("url_uid")
	existUrlUid := len(urlUid) > 0

	if tenantUserUid != "" {
		// 付费用户走直接报备流程
		requestDto.ReportSourceType = "DIRECT"
		requestDto.ResponsiblePersonGuid = authorize.GetTenantUserId(ctx)
		requestDto.ResponsiblePersonName = authorize.GetUserName(ctx)
		requestDto.ResponsiblePersonMobile = authorize.GetMobilePhone(ctx)
	} else {
		// 非付费用户走分享报备流程
		dto := &reportDto.ReportInfoRequestDto{
			Code: urlUid,
		}
		ri, err := c.reportService.ReportInfo(ctx, dto)
		if err != nil {
			stark.Logger.Errorf(ctx, "post参数json 不包含clue_source_id，err:%v", err)
			c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
			return
		}

		if ri.TenantReportId != "" {
			stark.Logger.Errorf(ctx, "该分享已经报备了，报备ID:%s", ri.TenantReportId)
			c.Fail(ctx, errcode.COMMON_ERROR, "该分享已经报备了")
			return
		}

		//params["report_source_type"] = "SHARE"
		//params["report_source_id"] = ri.Uid
		//params["clue_source"] = ri.ClueSource
		//params["clue_source_id"] = ri.ClueSourceId
		//params["responsible_person_guid"] = ri.SharerUserTenantId
		//params["responsible_person_name"] = ri.SharerUserName
		requestDto.ReportSourceType = "SHARE"
		requestDto.ReportSourceId = ri.Uid
		requestDto.ClueSource = ri.ClueSource
		requestDto.ClueSourceId = ri.ClueSourceId
		requestDto.ResponsiblePersonGuid = ri.SharerUserTenantId
		requestDto.ResponsiblePersonName = ri.SharerUserName
		requestDto.ResponsiblePersonMobile = ri.SharerUserMobile
	}

	_, reportId, err := c.reportService.Save(ctx, &requestDto)
	if err != nil {
		if !strings.Contains(err.Error(), "报备已存在") {
			stark.Logger.Errorf(ctx, "Save 报备保存失败，错误信息：%s", err.Error())
		}
		c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
		return
	}

	// 非付费用户的报备更新状态
	if tenantUserUid == "" && existUrlUid {
		globalUserId := authorize.GetGlobalUserId(ctx)
		updateData := &microGfyxUserService.ReportFromSharing{
			SubmitterName:    requestDto.Submitter,
			TenantReportId:   reportId,
			ReportStatusCode: 1,
			ReportStatus:     "跟进中",
			ClueSourceTitle:  requestDto.ProjectTitle,
			CompanyName:      requestDto.CompanyName,
			CityCode:         requestDto.ProjectCityCode,
			ProvinceCode:     requestDto.ProjectProvinceCode,
		}
		_, err = c.reportService.UpdateReportShare(ctx, globalUserId, urlUid, updateData)
		if err != nil {
			stark.Logger.Errorf(ctx, "Save UpdateReportShare err：%s", err.Error())
			c.Fail(ctx, errcode.COMMON_ERROR, err.Error())
			return
		}
	}

	c.Success(ctx, map[string]string{"report_id": reportId})
}

func (c *ReportController) GetReport(ctx *gin.Context) {
	//c.SetTenantCodeWithReportUrl(ctx)
	reportId := ctx.Query("report_id")
	data, err := c.reportService.GetReport(ctx, reportId)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetReport reportId:%s, err:%s", reportId, err.Error())
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	c.Success(ctx, data)

}

func (c *ReportController) GetMyList(ctx *gin.Context) {
	//c.SetTenantCodeWithReportUrl(ctx)
	// 检查数据数据
	var requestDto reportDto.ReportMyListRequestDto
	err := ctx.ShouldBind(&requestDto)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetMyList 参数错误 err:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, "参数错误")
		return
	}

	list, err := c.reportService.GetMyReportList(ctx, &requestDto)
	if err != nil {
		stark.Logger.Infof(ctx, "GetMyList GetMyReportList err:%s", err.Error())
		c.Fail(ctx, errcode.REPORT_MY_LIST_GET_RECORD, "获取数据失败")
		return
	}

	c.Success(ctx, list)
}

func (c *ReportController) GetRegionList(ctx *gin.Context) {
	//c.SetTenantCodeWithReportUrl(ctx)
	var requestDto reportDto.ReportMyListRequestDto
	err := ctx.ShouldBind(&requestDto)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetRegionList 参数错误 err:%s", err.Error())
		c.Fail(ctx, errcode.REPORT_MY_LIST_TRANS_FAILED, "参数错误")
		return
	}
	list, err := c.reportService.GetRegionReportList(ctx, &requestDto)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetRegionList request:%+v, 参数错误 err:%s", requestDto, err.Error())
		c.Fail(ctx, errcode.REPORT_MY_LIST_GET_RECORD, "获取数据失败")
		return
	}
	c.Success(ctx, list)
}

func (c *ReportController) GetReportStat(ctx *gin.Context) {
	data, err := c.reportService.GetReportStat(ctx)
	if err != nil {
		stark.Logger.Errorf(ctx, "GetReportStat err:%s", err.Error())
		c.Fail(ctx, errcode.COMMON_PARAMS_ERROR, err.Error())
		return
	}
	c.Success(ctx, data)

}
